"use server"
import {sessionOptions, SessionData, defaultSession} from "@/lib";
import {getIronSession} from "iron-session";
import {cookies} from "next/headers";
import {redirect} from "next/navigation";
import {revalidatePath} from "next/cache";

let username = "admin"
let isPro = true

export async function getSession() {
    const cookieStore = await cookies();
    const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
    if (!session.isLoggedIn) {
        session.isLoggedIn = defaultSession.isLoggedIn;
    }
    return session
}

export async function login(prevState: {error: undefined | string}, formData: FormData) {
    const session = await getSession();
    const formUsername = formData.get("username") as string;
    const formPassword = formData.get("password") as string;
    // CHECK USER IN THE DB
    // const user = await db.getUser({username, formPassword})

    if (formUsername !== username) {
        return {error: "Wrong Credentials"};
    }

    session.userId = "1";
    session.username = formUsername;
    session.isPro = isPro;
    session.isLoggedIn = true;

    await session.save();
    redirect("/")
}

export async function logout() {
    const session = await getSession();
    session.destroy();
    redirect("/");
}


export async function changePremium() {
    const session = await getSession();
    isPro = !session.isPro;
    session.isPro = isPro;
    await session.save();
    revalidatePath("/profile");
}